package com.mytest.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.mytest.pojo.ProductInfo;
import com.mytest.service.ProductInfoservice;
import com.mytest.utils.FileNameUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @BelongsProject: java-85-course-code
 * @BelongsPackage: com.mytest.controller
 * @Author: LiTongMiao
 * @Date: 2022/2/2 20:53
 * @Description: TODO
 */
@Controller
@RequestMapping("/prod")
public class ProductInfoAction {
    //每页显示的记录数
     public static final int PAGE_SIZE=5;

    //界面层，一定有业务逻辑层的对象
    @Autowired
    ProductInfoservice productInfoservice;

    //显示全部商品不分页
    @RequestMapping("/getAll")
    public String getAll(HttpServletRequest request){
        List<ProductInfo> list = productInfoservice.getAll();
        request.setAttribute("list",list);
        return "product";
    }

    //显示第1-5页记录
    @RequestMapping("/split")
    public String split(HttpServletRequest request){
        //得到第一页的数据,每页5条
        PageInfo info=productInfoservice.splitPage(1,PAGE_SIZE);
        request.setAttribute("info",info);
        System.out.println(info);
        return "product";
    }
    //ajax分页翻页处理
    @ResponseBody
    @RequestMapping("/ajaxSplit")
    public void ajaxSplit(int page, HttpSession session){
        //取得当前page参数的页面的数据
        PageInfo info=productInfoservice.splitPage(page,PAGE_SIZE);
        session.setAttribute("info",info);
    }
    //异步ajax文件上传处理(由本地上传到服务器端指定目录)
    @ResponseBody
    @RequestMapping("/ajaxImg")
    public Object ajaxImg(MultipartFile pimage,HttpServletRequest request) {
        //提取生成文件名UUID+上传图片的后缀.jpg .png
        String saveFileName = FileNameUtil.getUUIDFileName() + FileNameUtil.getFileType(pimage.getOriginalFilename());
        //得到项目中图片存储的路径
        String path=request.getServletContext().getRealPath("/image_big");
        //转存  E:idea_workspace\misssm\img_bg\3432ndjfhiejsnoejkdnfe.png
        try {
            pimage.transferTo(new File(path+File.separator + saveFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回客戶端json对象，封装图片路径，为了在界面显示立即回显
        JSONObject obj = new JSONObject();
        obj.put("imgurl",saveFileName);
        return obj.toString();
    }
}
